#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <android/log.h>

#define TAG "Socket_Service"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__);
#define ERROR(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__);

#define UNIX_DOMAIN "/tmp/UNIX_SOCKET"

int main(int argc, char **argv) {
    struct sockaddr_un srv_addr;
    struct sockaddr_un clt_addr;
    int fd, clt_len, clt_fd, ret;
    char recv_buf[1024];

    // 1.创建server socket
    fd = socket(PF_UNIX, SOCK_STREAM, 0);
    if (fd < 0) {
        ERROR("Failed to open socket '%s': %s\n", UNIX_DOMAIN, strerror(errno));
        return -1;
    }
    // 2.bind
    srv_addr.sun_family=AF_UNIX;
    strcpy(srv_addr.sun_path, UNIX_DOMAIN);
    ret = unlink(srv_addr.sun_path);
    if (ret != 0 && errno != ENOENT) {
        ERROR("Failed to unlink old socket '%s': %s\n", UNIX_DOMAIN, strerror(errno));
        goto out_close;
    }
    ret = bind(fd, (struct sockaddr *)&srv_addr, sizeof(srv_addr));
    if (ret == -1) {
        ERROR("Failed to bind socket\n");
        goto out_unlink;
    }

    // 3.listen
    ret = listen(fd, 5);
    if (ret == -1) {
        ERROR("Failed to listen socket\n");
        goto out_unlink;
    }

    // 4.accept
    clt_len = sizeof(clt_addr);
    clt_fd = accept(fd, (struct sockaddr *) &clt_addr, (socklen_t *)&clt_len);
    if (clt_fd < 0) {
        ERROR("Failed to listen socket\n");
        goto out_unlink;
    }

    // 5.read write
    memset(recv_buf, 0, 1024);
    read(clt_fd, recv_buf, sizeof(recv_buf));
    LOGD("Message from client: %s", recv_buf);

    // 6.close
    unlink(srv_addr.sun_path);
    close(fd);
    return 0;

out_unlink:
    unlink(srv_addr.sun_path);
out_close:
    close(fd);
    return -1;
}